<% 
	var headContent = {
	include("/STATIC/TEMPLATE/head.html",{HEAD_TITLE:'fixi-music音乐播放'}){}
%>
	<link rel="stylesheet" type="text/css" href="css/default.css">
	<style type="text/css">
			body {
				height: 100%;
				text-align: center;
				background: #c1c1c1 url(img/bg2.jpg) no-repeat;
				background-size: 100%;
			}
	</style>
<%
};

var bodyContent = {
%>
	<div class="">
		<div class="text-center">
			<h1 style="font-size: 2.5em;">Fixi Music</h1>
		</div>
		<h1>正在播放：${song.songName!"暂无"}</h1>
		<canvas id='canvas' width="800" height="300" style="position: relative;"></canvas>
		<br>
		<br>
		<audio id="audio">audio element not supported</audio>
		<br/>
		<div class="" id="lrc" style="font-size: 1.5em;">

		</div>
	</div>

    <!-- 自定义插件 -->
    <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" charset="utf-8">
			document.getElementById("audio").src = '${song.songLocation}';
			/* * 
			 * audio visualizer with html5 audio element
			 *
			 * v0.1.0
			 * 
			 * licenced under the MIT license
			 * 
			 * see my related repos:
			 * - HTML5_Audio_Visualizer https://github.com/wayou/HTML5_Audio_Visualizer
			 * - 3D_Audio_Spectrum_VIsualizer https://github.com/wayou/3D_Audio_Spectrum_VIsualizer
			 * - selected https://github.com/wayou/selected
			 * - MeowmeowPlayer https://github.com/wayou/MeowmeowPlayer
			 * 
			 * reference: http://www.patrick-wied.at/blog/how-to-create-audio-visualizations-with-javascript-html
			 */

			window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;

			window.onload = function() {
				var audio = document.getElementById('audio');
				var ctx = new AudioContext();
				var analyser = ctx.createAnalyser();
				var audioSrc = ctx.createMediaElementSource(audio);
				// we have to connect the MediaElementSource with the analyser 
				audioSrc.connect(analyser);
				analyser.connect(ctx.destination);
				console.log(audioSrc.connect(analyser));
				// we could configure the analyser: e.g. analyser.fftSize (for further infos read the spec)
				// analyser.fftSize = 64;
				// frequencyBinCount tells you how many values you'll receive from the analyser
				var frequencyData = new Uint8Array(analyser.frequencyBinCount);
				console.log(frequencyData);
				// we're ready to receive some data!
				var canvas = document.getElementById('canvas'),
					cwidth = canvas.width,
					cheight = canvas.height - 2,
					meterWidth = 10, //width of the meters in the spectrum
					gap = 2, //gap between meters
					capHeight = 2,
					capStyle = '#fff',
					meterNum = 800 / (10 + 2), //count of the meters
					capYPositionArray = []; ////store the vertical position of hte caps for the preivous frame
				ctx = canvas.getContext('2d'),
					gradient = ctx.createLinearGradient(0, 0, 0, 300);
				gradient.addColorStop(1, '#0f0');
				gradient.addColorStop(0.5, '#ff0');
				gradient.addColorStop(0, '#f00');
				//  var a1024 = [];
				//  for(var i = 0;i<1024;i++){
				//  	a1024[i] = 0;
				//  }
				// loop
				function renderFrame() {
					var array = new Uint8Array(analyser.frequencyBinCount);
					analyser.getByteFrequencyData(array);
					//      if(array != a1024){
					//      	console.log(array.length);
					//      }
					//      console.log(array.length);
					var step = Math.round(array.length / meterNum); //sample limited data from the total array
					ctx.clearRect(0, 0, cwidth, cheight);
					for (var i = 0; i < meterNum; i++) {
						var value = array[i * step];
						//          
						if (capYPositionArray.length < Math.round(meterNum)) {
							capYPositionArray.push(value);
						};
						ctx.fillStyle = capStyle;
						//draw the cap, with transition effect
						if (value < capYPositionArray[i]) {
							ctx.fillRect(i * 12, cheight - (--capYPositionArray[i]), meterWidth, capHeight);
						} else {
							ctx.fillRect(i * 12, cheight - value, meterWidth, capHeight);
							capYPositionArray[i] = value;
						};
						ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
						ctx.fillRect(i * 12 /*meterWidth+gap*/ , cheight - value + capHeight, meterWidth, cheight); //the meter
					}
					requestAnimationFrame(renderFrame);
				}

				renderFrame();
				audio.play();

			};
		</script>
		<script type="text/javascript">
		<% if( song.songLyric != null && '' != song.songLyric) { %>
			$.ajax({
				url: '${song.songLyric }',
				headers: {
					contentType: "application/x-www-form-urlencoded"
				},
				success: function(lrc) {
					var lyric = parseLyric(lrc);

					//					console.log(lyric);
					var i;
				
					var audio = document.getElementById('audio');
					lyricContainer = document.getElementById('lrc');
					audio.ontimeupdate = function(e) {
						//遍历所有歌词，看哪句歌词的时间与当然时间吻合
						//						console.log("播放器时间"+this.currentTime.toFixed());
						
						for (i = 0, l = lyric.length; i < l; i++) {
							if (this.currentTime /*当前播放的时间*/ > lyric[i][0]) {
								//								console.log("播放器时间"+this.currentTime);
								//								console.log("歌词时间"+lyric[i][0]);
								//显示到页面
								lyricContainer.textContent = lyric[i][1];

							};
						};
					};

				},

				error: function(e) {}
			});
			<% } %>			
			//			var audio = document.getElementsByTagName('audio');
			//				//显示歌词的元素
			//			lyricContainer = document.getElementById('lyricContainer');
			//			//监听ontimeupdate事件
			//			audio.ontimeupdate = function(e) {
			//				//遍历所有歌词，看哪句歌词的时间与当然时间吻合
			//				for (var i = 0, l = lyric.length; i < l; i++) {
			//					if (this.currentTime /*当前播放的时间*/ > lyric[i][0]) {
			//						//显示到页面
			//						lyricContainer.textContent = that.lyric[i][1];
			//					};
			//				};
			//			};
			function parseLyric(text) {
				//将文本分隔成一行一行，存入数组
				var lines = text.split('\n'),
					//用于匹配时间的正则表达式，匹配的结果类似[xx:xx.xx]
					pattern = /\[\d{2}:\d{2}.\d{2}\]/g,
					//保存最终结果的数组
					result = [];
				//去掉不含时间的行
				while (!pattern.test(lines[0])) {
					lines = lines.slice(1);
				};
				//上面用'\n'生成生成数组时，结果中最后一个为空元素，这里将去掉
				lines[lines.length - 1].length === 0 && lines.pop();
				lines.forEach(function(v /*数组元素值*/ , i /*元素索引*/ , a /*数组本身*/ ) {
					//提取出时间[xx:xx.xx]
					var time = v.match(pattern),
						//提取歌词
						value = v.replace(pattern, '');
					//因为一行里面可能有多个时间，所以time有可能是[xx:xx.xx][xx:xx.xx][xx:xx.xx]的形式，需要进一步分隔
					time.forEach(function(v1, i1, a1) {
						//去掉时间里的中括号得到xx:xx.xx
						var t = v1.slice(1, -1).split(':');
						//将结果压入最终数组
						result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
					});
				});
				//最后将结果数组中的元素按时间大小排序，以便保存之后正常显示歌词
				result.sort(function(a, b) {
					return a[0] - b[0];
				});
				return result;
			}
		</script>
    
   
<%}; %>
<% layout("/STATIC/TEMPLATE/_layout.html",{head:headContent,body:bodyContent}){ %>
<%}; %>